package cn.tsmchina.one.service.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.tsmchina.one.dao.BaseDaoSupport;
import cn.tsmchina.one.dao.user.UserDao;
import cn.tsmchina.one.domain.user.User;

/**
 * Description:
 * @author zhaoying 
 * @date 2013-10-4
 * @version 1.0
 * Copyright: Copyright (c) 2013 TSM,Inc
 */
@Service
public class UserServiceImpl extends BaseDaoSupport<User> implements UserService {
	@Autowired
	private UserDao userDao;

	@Override
	//用户注册
	public Long addUser(User user, long customerId) {
		if(isExists(user.getPhone(), customerId)){
			return new Long(-1);
		}
		return userDao.addUser(user);
	}
	
	//用户是否存在
	private boolean isExists(String phone, long customerId){
		if(!StringUtils.isEmpty(phone)){
			User user = userDao.getUserByPhone(phone, customerId);
			if(null != user)
				return true;
		}
		return false;
	}

	@Override
	public User loginValid(String phone, String password, long customerId) {
		return userDao.getUser(phone, password, customerId);
	}

	@Override
	public User updateUser(User user) {
		Long userId = user.getId();
		
		if(null != userId){
			int updateNum = userDao.updateUser(user);
			if(updateNum >0){
				return userDao.getUserById(userId.toString());
			}
		}
		
		return null;
	}

	@Override
	public boolean updateUserPass(User user) {
		int updateNum = userDao.updateUserPass(user);
		if(updateNum >0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public void update(User user) {
		super.update(user);
	}

	@Override
	public void updateUserCredits(long userId, int creditsChange) {
		User user = getUser(userId);
		user.setCredits(user.getCredits()+creditsChange);
		update(user);
	}
	
	@Override
	public User getUser(long userId) {
		return userDao.getUserById(""+userId);
	}
}

